//
//  ViewController.swift
//  popover
//
//  Created by 李煜 on 2022/9/14.
//

import UIKit

class AViewController: UIViewController, UIPopoverPresentationControllerDelegate {
  @IBOutlet var btn: UIButton!

  override func viewDidLoad() {
    super.viewDidLoad()
    title = "控制器A"
    //    设置右导航
    setupNavigationItem()
  }

  func setupNavigationItem() {
    let barItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(clickNaviItemAdd(item:)))
    navigationItem.rightBarButtonItem = barItem
  }

  // MARK: - 事件

  //  点击item
  @objc private func clickNaviItemAdd(item: UIBarButtonItem) {
    print("click add.")
    let b = BViewController()
    b.modalPresentationStyle = .popover
    b.preferredContentSize = CGSizeMake(100, 100)
    b.popoverPresentationController?.barButtonItem = item
    b.popoverPresentationController?.delegate = self
    present(b, animated: true)
  }

  func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
    .none
  }

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    btn.bounds = .init(x: 0, y: 0, width: 100, height: 100)
  }

  //  点击按钮
  @IBAction func clickBtn(_ sender: UIButton) {
    let b = BViewController(nibName: nil, bundle: nil)
    b.modalPresentationStyle = .popover
    b.preferredContentSize = .init(width: 100, height: 100)
    b.popoverPresentationController?.delegate = self
    b.popoverPresentationController?.sourceView = sender
    b.popoverPresentationController?.sourceRect = .init(x: -0, y: -0, width: 50, height: 50)
    print(sender.frame)
//    b.popoverPresentationController?.permittedArrowDirections = .up
    present(b, animated: true)
  }
}
